using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Repo.Helpers;
using SPRepoDemo.Web.Helpers;

namespace SPRepoDemo.Web.Features.DeploySPRepositoryDemo
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("40ab112f-3b73-4c9d-9d17-1c28d371c00e")]
    public class DeploySPRepositoryDemoEventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                using (var web = properties.Feature.Parent as SPWeb)
                {
                    if (web != null)
                    {
                        //DeploymentHelper.ApplyCustomMasterPage(web, "sps.master");
                        DeploymentHelper.SetHomePage(web, "/Pages/DemoHome.aspx");

                        var listsToCreate = ListHelper.GetListsToCreate(web.Site, "/_layouts/SPRepoDemo.Web/Lists.xml");
                        foreach (var listToCreate in listsToCreate)
                        {
                            var thisWeb = (listToCreate.Web == "/") ? web : WebHelper.GetWeb(web, listToCreate.Web);
                            ListHelper.CreateList(thisWeb, listToCreate);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                LoggingHelper.ErrorLog(exception);
                throw;
            }
        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                using (var web = properties.Feature.Parent as SPWeb)
                {
                    if (web != null && web.IsRootWeb)
                    {
                        DeploymentHelper.RemoveCustomMasterPage(web);
                        DeploymentHelper.SetHomePage(web, "/Pages/default.aspx");
                    }
                }
            }
            catch (Exception exception)
            {
                LoggingHelper.ErrorLog(exception);
                throw;
            }
        }
    }
}
